package com.jxzn.locust.config;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import com.jxzn.locust.exception.PermissionException;
import com.jxzn.locust.service.business.PermissionService;
import com.jxzn.locust.support.Auth;
import com.jxzn.locust.support.Module;

/**
 * 权限验证
 * 
 * @author EDZ
 *
 */
@Component
public class PermissionInterceptorHandler implements HandlerInterceptor {

    @Autowired
    PermissionService permissionService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod hm = ((HandlerMethod) handler);
        
        Module module = hm.getBeanType().getAnnotation(Module.class);

        Auth auth = hm.getMethodAnnotation(Auth.class);
        if (null == auth) {
            return true;
        }
        if (!permissionService.checkSystemPermission(request.getSession(), module, auth)) {
            throw new PermissionException();
        }
        return true;
    }
}
